#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main()
{
  int serv_sock,clnt_sock;
  struct sockaddr_in serv_addr,clnt_addr;
  socklen_t clt_sz = sizeof(clnt_addr);
  // ipv4 or ipv6, SOCK_STREAM or SOCK_DGRAM, tcp or udp
  // 0代表系统自动推断tcp or udp
  serv_sock = socket(PF_INET,SOCK_STREAM,0);
  memset(&serv_addr,0,sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  serv_addr.sin_port = htons(8000);
  printf("running at 127.0.0.1:8000\n");
  bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
  listen(serv_sock,20);
  while (1)
  {
    clnt_sock = accept(serv_sock,(struct sockaddr*)&clnt_addr,&clt_sz);
    char head[10240] = "HTTP/1.1 200 OK\r\ncontent-type:";
    FILE* clnt_read;
    clnt_read = fdopen(clnt_sock,"r");
    char req_line[100];
    fgets(req_line,100,clnt_read);
    char file_name[30]="/";
    printf(req_line);
    
    int i;
    for(i=5;req_line[i]!=' ';i++){
      file_name[i-5]=req_line[i];
    }
    printf(file_name);
    if(strcmp(file_name,"/")==0||strcmp(file_name,"favicon.ico")==0){
      strcpy(file_name,"index.html");
    }
    int len=strlen(file_name);
    if(file_name[len-2]=='m'){
       strcat(head,"text/html");
    }else if(file_name[len-2]=='j'){
       strcat(head,"application/javascript");
    }else if(file_name[len-2]=='s'){
       strcat(head,"text/css");
    }
    FILE *fp = NULL;
    char str[10240];
    int buff;
    i=0;
    char length[30];
    printf(file_name);
    fp = fopen(file_name, "r");
    do{
      buff=fgetc((FILE*)fp);
      str[i]=buff;
      i++;
    }while(buff!=EOF);
    fclose(fp);
    printf("%s\n",str);
    printf("%d\n",i);
    sprintf(length,"%d",i-1);
    strcat(head,"\r\nContent-length:");
    strcat(head,length);
    strcat(head,"\r\n\r\n");
    strcat(head,str);
    write(clnt_sock, head, sizeof(head));
    close(clnt_sock);
    }
   close(serv_sock);
   return 0;
}